import os.path
import random

from qiniu import Auth, put_file, etag, put_data
import qiniu.config
from werkzeug.utils import secure_filename

import settings


def upload_qiniu(filestorage):
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'GNWe-Juysil6XvybZxuNA7u-7tJgBXmTcPx_NAIb'
    secret_key = 'UOCDDtyK78VopfwU3o_VqXLF50Ap9NkEls2JXxiw'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'daftv01'
    # 上传后保存的文件名
    filename = secure_filename(filestorage.filename)
    name = filename.rsplit('.')[0]
    suffix = filename.rsplit('.')[-1]
    ran = random.randint(1, 1000)
    key = name + '_' + str(ran) + '.' + suffix
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)

    ret, info = put_data(token, key, filestorage.read())
    return info, key
